<template>
  <div>
    <div class="search-header">
      <!-- 后退按钮 -->
      <van-icon
        name="arrow-left"
        color="white"
        size="18"
        class="goback"
        @click="$router.back({ path: '/home' })"
      />
      <!-- 搜索组件 -->
      <van-search
        placeholder="请输入搜索关键词"
        background="#007BFF"
        shape="round"
        v-model.trim="kw"
        v-focus
        @input="inputFn"
        @search='enterFn'
      />
    </div>
    <!-- 搜索建议列表 -->
    <div class="sugg-list" v-if="kw">
      <div
        class="sugg-item"
        v-for="(str, index) in suggestionList"
        :key="index"
        v-html="lingtFn(str)"
        @click="suggClickFn(str)"
      ></div>
    </div>
    <!-- 搜索历史 -->
    <div class="search-history" v-else>
      <!-- 标题 -->
      <van-cell title="搜索历史">
        <!-- 使用 right-icon 插槽来自定义右侧图标 -->
        <template #right-icon>
          <van-icon name="delete" class="search-icon" @click="clearHistoryFN"/>
        </template>
      </van-cell>

      <!-- 历史列表 -->
      <div class="history-list">
        <span @click="$router.push({path:`/search/${item}`})" class="history-item" v-for="item,index in history" :key="index">{{item}} </span>
      </div>
    </div>
  </div>
</template>

<script>
import { suggestionAPI } from '@/api'
// 导入自己封装的 storage方法
import { setStorage, removetStorage } from '@/utils/storage'
export default {
  data () {
    return {
      kw: '', // 搜索关键字
      timer: null, // 输入框防抖初始值
      suggestionList: [], // 联想列表
      history: JSON.parse(localStorage.getItem('history')) || []// 搜索历史
    }
  },
  methods: {
    inputFn () {
      // 每次触发事件,就把上一次的定时器清除掉
      clearTimeout(this.timer)
      // 把要进行的操作用定时器包裹
      this.timer = setTimeout(async () => {
        if (this.kw.length !== 0) {
          const res = await suggestionAPI({ q: this.kw })
          this.suggestionList = res.data.data.options
        } else {
          this.suggestionList = []
        }
      }, 300)
    },
    // 关键字高亮
    lingtFn (str) {
      const reg = new RegExp(this.kw, 'ig')
      return str.replace(reg, (match) => {
        return `<span style="color:red">${match}</span>`
      })
    },
    // 输入框回车
    enterFn () {
      this.history.push(this.kw) // 将关键字存进搜索历史
      this.history = Array.from(new Set(this.history)) // 数组去重,避免重复存储
      setStorage('history', JSON.stringify(this.history)) // 因后台无搜索历史接口,暂时将其存储本地
      this.$router.push({
        path: `/search/${this.kw}`
      })
    },
    // 点击联想列表
    suggClickFn (str) {
      this.history.push(str)// 将联想列表的文字存进搜索历史
      this.history = Array.from(new Set(this.history)) // 数组去重,避免重复存储
      setStorage('history', JSON.stringify(this.history)) // 因后台无搜索历史接口,暂时将其存储本地
      this.$router.push({
        path: `/search/${str}`
      })
    },
    // 清空历史列表
    clearHistoryFN () {
      this.history = []
      removetStorage('history') // 移除本地存储
    }
  }
}
</script>

<style scoped lang="less">
.search-header {
  height: 46px;
  display: flex;
  align-items: center;
  background-color: #007bff;
  overflow: hidden;
  /*后退按钮*/
  .goback {
    padding-left: 14px;
  }
  /*搜索组件*/
  .van-search {
    flex: 1;
  }
}
/*搜索建议列表样式 */
.sugg-list {
  .sugg-item {
    padding: 0 15px;
    border-bottom: 1px solid #f8f8f8;
    font-size: 14px;
    line-height: 50px;
    // 实现省略号的三行代码
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }
}
/**搜索历史 */
.search-icon {
  font-size: 16px;
  line-height: inherit;
}

.history-list {
  padding: 0 10px;
  .history-item {
    display: inline-block;
    font-size: 12px;
    padding: 8px 14px;
    background-color: #efefef;
    margin: 10px 8px 0px 8px;
    border-radius: 10px;
  }
}
</style>
